package equitiestailor

import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.springframework.web.multipart.commons.CommonsMultipartFile

class FileUploadService {

    static transactional = true

    def String createImage(directory,params,request){
        // save file
        def servletContext = ServletContextHolder.servletContext
        def storagePath = servletContext.getRealPath(directory)
        def CommonsMultipartFile uploadedFile
        try {
            uploadedFile= params.img
        }
        catch (Exception e){
            e.printStackTrace()
            return ""
        }
        def fileName = uploadedFile.originalFilename
        
        def storagePathDir = new File(storagePath)
        if (!storagePathDir.exists()){
            storagePathDir.mkdirs()
        }
            
        def downloadedFile = request.getFile('img')
        if (!downloadedFile.empty){
            def img = new File(storagePathDir.getAbsolutePath()+File.separatorChar+fileName)
            downloadedFile.transferTo(img)
            return directory+"/"+fileName
        }
        return ""       
    }
}